'use strict';
const fs = require('fs');
const path = require('path');
var Process = require('child_process');
var fileObj = new Object();
var watcher = null;
let exportPath = "";
var exportCode = "";
var projPath = "";
const writeFile = async function (filePath, txt) {

	fs.writeFile(filePath, txt, (err) => {
		if (err) {
			console.error("保存文件失败=" + err);
		} else {
			//console.log("保存成功");
        }
	});
};
module.exports = {

	load() {
		let dirPath = path.resolve(__dirname + "/../../")
		exportPath = path.join(dirPath, "./library/reloadCode/")
		exportCode = path.join(dirPath, "./library/reloadCode/file.json")
		projPath = path.join(dirPath, "./assets/script/")
		// 当 package 被正确加载的时候执行
		 try {
			 watcher = fs.watch(projPath, { recursive: true }, async (event, filename) => {
				 if (filename.endsWith(".ts")) {
					 if(!fs.existsSync(exportCode)){
						 fileObj = new Object();
					 }
					 let filenameTxt = filename.replace(".ts",".txt")
					 fileObj[filenameTxt] = Date.parse(new Date());
					 await writeFile(exportCode, JSON.stringify(fileObj));
					 let srcFile = path.join(projPath, filename)
					 let destFile = path.join(exportPath, filename)
					 const destDir = path.dirname(destFile);

					 // 确保目标文件夹存在
					 if (!fs.existsSync(destDir)) {
						 fs.mkdirSync(destDir, { recursive: true });
					 }
					 destFile = destFile.replace(".ts",".txt")
					 fs.copyFileSync(srcFile, destFile);
					 //let url = "http://localhost:7456/assets/internal/import/reloadCode/" + filename

					 console.log(srcFile, "->", destFile);
					 //console.log("AAAAAAA", url)
					 //let module = require(destFile);
	
					 //console.log("WEEEEEEEEEEEEE=", JSON.stringify(module))
					
				 }
				 
			 })

		} catch {

		}

	},

	unload () {
		// 当 package 被正确卸载的时候执行
		watcher.close()

	},

	methods: {
		
		
		async reloadCode() {

			//await writeFile(root.name.value,txt);
		},
		
	}
};
